package com.zretc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import com.zretc.config.AlipayConfig;
import com.zretc.entity.Order;
import com.zretc.entity.OrderDetail;
import com.zretc.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: bLUeSuMMerDreamer
 * @createTime: 2020-08-26 15:41
 */
@RequestMapping("/order")
@CrossOrigin
@Controller
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private OrderService orderService;

    @RequestMapping(value = "/getStatistics", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getStatistics(@RequestParam String sellerAccount, @RequestParam String groupBy) {

        Map<String, Object> params = new HashMap<>();
        if (sellerAccount != null && !"".equals(sellerAccount))
            params.put("sellerAccount", sellerAccount);
        if (groupBy != null && !"".equals(groupBy))
            params.put("groupBy", groupBy);
        return orderService.getStatistics(params);
    }

    @RequestMapping(value = "/getOrderBySeller", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<List<OrderDetail>> getOrderBySeller(
            @RequestParam String sellerAccount,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam String keyword,
            Integer status,
            String orderBy,
            Boolean desc) {
        Map<String, Object> params = new HashMap<>();
        //if (keyword != null && !"".equals(keyword)) {
        String[] keywords = keyword.trim().split(" ");
        if (keywords.length > 1) {
            int i = 0;
            for (String s : keywords) {
                params.put("keyword" + (i == 0 ? "" : i), "%" + s.trim() + "%");
                i++;
            }
        } else {
            params.put("keyword", "%" + keyword.trim() + "%");
        }
        //}
        if (orderBy != null && !"".equals(orderBy)) {
            params.put("orderBy", orderBy);
            if (desc)
                params.put("desc", true);
        }

        params.put("status", status);
        params.put("sellerAccount", sellerAccount);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        PageInfo<OrderDetail> ordersByParams = orderService.getOrderDetailsByParams(params);
        if (ordersByParams.getList() == null || ordersByParams.getList().size() == 0) {
            return new ResponseEntity(null, HttpStatus.NO_CONTENT);
        } else {
            return new ResponseEntity(ordersByParams, HttpStatus.OK);
        }
    }

    /**
     * 根据订单构建支付宝交易信息并跳转页面
     *
     * @param :request
     * @param :response
     * @param :order
     * @return: void
     */
    @RequestMapping(value = "/payOrder")
    public void payOrder(@RequestParam(value = "orderId") String orderId, @RequestParam(value = "cost") Double cost, HttpServletResponse response, HttpServletRequest request) throws IOException, AlipayApiException {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setOrderPrice(cost);
        goToAliPay(request, response, order);
    }

    private void goToAliPay(HttpServletRequest request, HttpServletResponse response, Order order) throws AlipayApiException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + order.getOrderId() + "\"," +
                "\"total_amount\":\"" + order.getOrderPrice() + "\"," +
                "\"subject\":\"码上商城\"," +
                //"\"body\":\"激素的\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                //"\"goods_detail\":{\"goods_id\":\"" + order.getOrderId() + "\"  ,\"goods_name\":\"码上物流寄件服务\",\"quantity\":\"1\",\"price\":\"" + order.getCost() + "\"}" +
                "}");
        // 请求"
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        AlipayConfig.logResult(result);// 记录支付日志
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(result);
    }

    /**
     * 支付完成后的回调Url
     *
     * @author: bLUeSuMMerDreamer
     * @date: 2020/7/26 3:29
     * @param: request
     * @param: response
     * @return: void
     */
    @RequestMapping(value = "/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {

//        Map<String, Object> setParam = new HashMap<>();
//        setParam.put("state", 1);
//        Map<String, Object> whereParam = new HashMap<>();
//        whereParam.put("orderId", request.getParameter("out_trade_no"));
//        orderService.updateOrderByParam(setParam, whereParam);
        //设置支付成功重定向页面
        response.sendRedirect("/index" + request.getParameter("out_trade_no"));
        //验签交易信息
        //boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名


    }
}
